using System.Collections;
using System.Collections.Generic;
using System.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using Platform;
using Platform.CharacterData;
using Platform.Skill.Deployer;
using UnityEngine;
using Plugin.Tool;

namespace GardeningSkeleton.Platform.SkillSpace
{
    public class ThunderStrikeDeployer : SkillDeployer
    {
        private CharacterStats targetStats;

        private bool triggered;

        [SerializeField] private float speed;

        public void Start()
        {
            anim = GetComponentInChildren<Animator>();
        }
        public override void DeploySkill()
        {
            base.DeploySkill();
            
            targetStats = skillData?.attackTargets != null ? skillData.attackTargets.FirstOrDefault()?.GetComponent<CharacterStats>() : null;
            if (targetStats == null)
            {
                Release();
                skillData.combo = 0;
                skillData.lastTarget = null;
            }
        }

        void Update()
        {
            if (triggered || targetStats == null) return;
            transform.position = Vector2.MoveTowards(transform.position, targetStats.entity.GetRealPos(), speed * Time.deltaTime);
            transform.right = transform.position - targetStats.entity.GetRealPos();

            if (Vector2.Distance(transform.position, targetStats.entity.GetRealPos()) < 0.1f)
            {
                var originRotation = anim.transform.localRotation;
                //从天而降的效果
                anim.transform.localPosition = new Vector3(0, 0.5f);
                anim.transform.localRotation = Quaternion.identity;

                transform.localRotation = Quaternion.identity;
                transform.localScale = new Vector3(3, 3);

                triggered = true;
                anim.SetTrigger("Hit");

                //链式反应
                if (skillData.attackTargets.Count > 0 && skillData.comboCount > skillData.combo)
                {
                    Debug.Log("链式反应");
                    OwnerEntity.UseSkill(SkillEnum.ThunderStrike, transform.position);
                    skillData.combo++;
                }
                else
                {
                    // 清除共有的数据
                    skillData.combo = 0;
                    skillData.lastTarget = null;
                }

                ZTimer.SetTimeout(0.2f, () =>
                {
                    triggered = false;
                    AttackStart();
                    Release();

                    anim.transform.localRotation = originRotation;
                    anim.transform.localPosition = Vector3.zero;
                    transform.localScale = new Vector3(1, 1);
                });
            }
        }
    }
}